package com.zm.zmgz.controller.businessdata;

import com.zm.zmgz.annotationzm.ButtonAuthorityAnnotation;
import com.zm.zmgz.pojo.*;
import com.zm.zmgz.service.EmployeeService;
import com.zm.zmgz.service.RevenueService;
import com.zm.zmgz.utils.ConfigureBean;
import com.zm.zmgz.utils.DateUtils;
import com.zm.zmgz.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/05/13/14:02
 * @Description:收支明细模块
 */
@RestController
@RequestMapping("/businessdata/revenue")
public class RevenueController {

    @Autowired
    RevenueService revenueService;

    @Autowired
    EmployeeService employeeService;


    @Autowired
    ConfigureBean configureBean; // 获取配置文件自定义属性

    /***
     * @Description: 通过url拼接出绝对地址,将图片从服务器中删除
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @DeleteMapping("/deletePictrueByUrl")
    public Response deletePictrueByUrl(HttpServletRequest request,String url) {
        // 通过url,服务器环境绝对地址;拼接出该图片在服务器的绝对地址,将之删除
        // url(http://localhost:8082/img/2020/06/09/d70af2f7-c188-476d-b52c-7df6de502f69.jpg)
        System.err.println(url);
        // 获取服务端绝对地址+/img(C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.8414520335987531999.8082\img)
        String filepath = request.getServletContext().getRealPath("/img");
        String[] imgs = url.split("img");
        // C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.8414520335987531999.8082\img/2020/06/09/d70af2f7-c188-476d-b52c-7df6de502f69.jpg
        String filePath = filepath + imgs[1];
        System.err.println(filePath);
        boolean b = FileUtils.deleteFileByfile(new File(filePath));
        return b ? new Response(20000, "文件删除成功!", true) : new Response(20000, "文件删除失败!", false);
    }

    /***
     * @Description: 获取批次选择数据(年月)
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @GetMapping("/getBatchOptions")
    public Response getBatchOptions() {
        List<ProjectProfitBatchOptionBean> list = revenueService.getBatchOptions();
        return !Objects.isNull(list) ? new Response(20000, "获取批次选择数据成功!", list) : new Response(20000, "获取批次选择数据失败!", null);
    }


    /***
     * @Description: 获取文件上传地址
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @GetMapping("/getUpFileAddress")
    public Response getUpFileAddress() {

        String upFileAddress = configureBean.getUpFileAddress();
        return !Objects.isNull(upFileAddress) ? new Response(20000, "获取文件上传地址成功!", upFileAddress) : new Response(20000, "获取文件上传地址失败!", null);
    }

    /***
     * @Description: 刷新某批次的项目统计记录(如果没有该批次记录,添加一条示范记录)
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @PostMapping("/refreshStatistics")
    @ButtonAuthorityAnnotation("/revenue/incomeAndExpenditureDetails/refreshTheBatch")
    public Response refreshStatistics(@RequestHeader("X-Token") String token,String date) {
        EmployeeBean employee = employeeService.getEmployeeByIdentificationnumber(token);
        CurrentUser.setIdCard(employee.getIdentificationnumber());
        CurrentUser.setName(employee.getName());
        System.err.println(date);
        Date date1 = DateUtils.getDateByString(date,"yyyy年MM月");
        boolean b = revenueService.refreshStatistics(date1);
        return b ? new Response(20000, "该批次的项目统计记录刷新成功!", true) : new Response(20000, "该批次的项目统计记录刷新失败!", false);
    }


    /***
     * @Description: 上传文件到webapp目录中
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-24 15:57:26
     */
    @PostMapping("/upfile")
    public Response upfile(@RequestParam MultipartFile file,HttpServletRequest request) {
//        System.err.println(fileName);
//        文件名
//        String name = file.getName();
//        System.err.println("name:"+name);
        String oldname = file.getOriginalFilename();
        System.out.println("旧名字:"+oldname);
        String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."));
//        String newname = UUID.randomUUID().toString() +".xlsx";
        System.out.println("新文件名:" + newname);
//        文件目录
        String filepath = request.getServletContext().getRealPath("/img");
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        String date = format.format(new Date());
        filepath += date;
        System.out.println("存储路径:" + filepath);
//        创建新文件
        File newfile = new File(filepath + newname);
        if (!newfile.exists()) {
            newfile.mkdirs();
        }
        System.out.println("新文件:" + newfile.getAbsolutePath());
//        保存文件
        try {
            file.transferTo(newfile);
//            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + date + newname;
            String url = request.getScheme() + "://" + configureBean.getServerAddress() + ":" + configureBean.getServerPort() + "/img" + date + newname;
            System.out.println("url:" + url);
            return new Response(20000, "图片上传成功!", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        返回url
        return new Response(20000, "图片上传失败!", null);
    }

    /***
     * @Description: 通过日期刷新该批次的收支明细数据
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @PostMapping("/refreshRevenueByDate")
    public Response refreshRevenueByDate(Date date) {
        boolean b = revenueService.refreshStatistics(date);
        return b ? new Response(20000, "收支明细数据刷新成功!", true) : new Response(20000, "收支明细数据刷新失败!", false);
    }

    /***
     * @Description: 提供日期获取收支明细数据
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @GetMapping("/getRevenuesByDate")
    public Response getRevenuesByDate(String date,Integer page, Integer limit) {
        System.err.println(date);
        Date date1 = DateUtils.getDateByString(date,"yyyy年MM月");
        List<RevenueBean> revenueBeanList = revenueService.getRevenuesByDate(date1,page,limit);
        return !Objects.isNull(revenueBeanList) ? new Response(20000, "获取收支明细数据成功!", revenueBeanList) : new Response(20000, "获取收支明细数据失败!", null);
    }


    /***
     * @Description: 添加一个收支明细记录
     * 如果日期与当前时间是同一个月份,填写日期为当前时间
     * 否则填写日期与日期一致
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @PostMapping("/addRevenue")
    @ButtonAuthorityAnnotation("/revenue/incomeAndExpenditureDetails/add")
    public Response addRevenue(@RequestHeader("X-Token") String token,@RequestBody RevenueBean revenueBean) {
        Date date = revenueBean.getCreationdate();
        Date date1 = revenueBean.getSettlementdate();
        if(Objects.isNull(date) || Objects.isNull(date1))
            return new Response(20000, "添加一个收支明细记录失败!(两个时间值不能为空!)", false);
        EmployeeBean employee = employeeService.getEmployeeByIdentificationnumber(token);
        CurrentUser.setIdCard(employee.getIdentificationnumber());
        CurrentUser.setName(employee.getName());
        revenueBean.setId(null);
        revenueBean.setCreateuser(CurrentUser.getName());
        int i = revenueService.addRevenue(revenueBean);
        return i == 1 ? new Response(20000, "添加一个收支明细记录成功!", true) : new Response(20000, "添加一个收支明细记录失败!", false);
    }

    /***
     * @Description: 删除一个收支明细记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @DeleteMapping("/deleteRevenue")
    @ButtonAuthorityAnnotation("/revenue/incomeAndExpenditureDetails/delete")
    public Response deleteRevenue(@RequestHeader("X-Token") String token, @RequestBody RevenueBean revenueBean) {
        int i = revenueService.deleteRevenue(revenueBean);
        return i == 1 ? new Response(20000, "删除一个收支明细记录成功!", true) : new Response(20000, "删除一个收支明细记录失败!", false);
    }

    /***
     * @Description: 更新一个收支明细记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-22 17:42:03
     */
    @PutMapping("/updateRevenue")
    @ButtonAuthorityAnnotation("/revenue/incomeAndExpenditureDetails/edit")
    public Response updateRevenue(@RequestHeader("X-Token") String token,@RequestBody RevenueBean revenueBean) {
        System.err.println(revenueBean);
        int i = revenueService.updateRevenue(revenueBean);
        return i == 1 ? new Response(20000, "更新一个收支明细记录成功!", true) : new Response(20000, "更新一个收支明细记录失败!", false);
    }


}
